﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;
using Lswweb.Model;
using Lswweb.Domain;

namespace Lswweb.Controls
{
    public class UserChangePassword : SkinnedWebControl
    {
        #region 成员字段和构造方法

        private Control oldPswPanel;
        private Label lbUserName;
        private TextBox tbxUserName;
        private TextBox txtOldPsw;
        private TextBox txtNewPsw;
        private TextBox txtNewPsw2;
        private Button btnConfirm;

        #endregion

        protected override void InitializeSkin(System.Web.UI.Control skin)
        {
            lbUserName = (Label)skin.FindControl("lbUserName");
            tbxUserName = (TextBox)skin.FindControl("tbxUserName");
            oldPswPanel = skin.FindControl("oldPswPanel");
            txtOldPsw = (TextBox)skin.FindControl("txtOldPsw");
            txtNewPsw = (TextBox)skin.FindControl("txtNewPsw");
            txtNewPsw2 = (TextBox)skin.FindControl("txtNewPsw2");
            btnConfirm = (Button)skin.FindControl("btnConfirm");

            btnConfirm.Click += new EventHandler(btnConfirm_Click);

            if(SiteContext.Current.Context.User.Identity.IsAuthenticated)
            {
                tbxUserName.Visible = false;
                lbUserName.Visible = true;
 
                //管理员更改会员密码
                if (UserId > 0 && UserId!=SiteContext.Current.User.Id && SiteContext.Current.User.IsAdmin)
                {
                    oldPswPanel.Visible = false;
                    UserInfo userInfo = Users.GetUser(UserId);

                    if(lbUserName!=null)
                        lbUserName.Text = userInfo.LoginName;
                }
                //会员更改自己密码
                else if (lbUserName != null)
                {
                    lbUserName.Text = SiteContext.Current.User.LoginName;
                }
            }
            //通过取回密码Url更改密码
            else
            {
                tbxUserName.Visible = true;
                lbUserName.Visible = false;

                Users.ValidateGetPasswordUrl();
                oldPswPanel.Visible = false;
            }
        }

        void btnConfirm_Click(object sender, EventArgs e)
        {
            string userName = SiteContext.Current.Context.User.Identity.IsAuthenticated ? lbUserName.Text : tbxUserName.Text.Trim();
            string oldPsw = txtOldPsw.Text.Trim();
            string newPsw = txtNewPsw.Text.Trim();
            UserSecurity.ChangePassword(userName,oldPsw,newPsw);
        }

        private int UserId
        {
            get { return SiteContext.Current.Id; }
        }

        protected override string DefaultSkinFilename
        {
            get { return "User/UserChangePassword.ascx"; }
        }
    }
}
